var mongoose=require('mongoose');
var Schema=mongoose.Schema;
var config=require('../config');
var User1=require('./user')
var db=mongoose.createConnection(config.db_url);
db.on('error',function(error){
    console.log(error);
});


var activeSchema=new Schema({
    activeDate:String,
    addr:String,
    language:String,
    cost:String,
    theme:String,
    discribe:String,
    applyNum:{type:Number,default:0}
});
//users---对应数据库表名
var Active=db.model('Active',activeSchema);

/**
 * 获得简介信息
 */

Active.prototype.findAllActive=function(callback){
    Active.find({},function(err,datas){
        callback(err,datas);
    })
}

Active.prototype.updateActiveById=function(id,options,callback){
    Active.update({_id:id},options,function(err){
        callback(err)
    });
}
Active.prototype.findActiveById=function(id,callback){
    Active.findOne({_id:id},function(err,data){
        callback(err,data);
    });
}
Active.prototype.delActiveById=function(id,callback){
    Active.remove({_id:id},function(err){
        callback(err);
    })
}
Active.prototype.updateApplyNum=function(id,num,callback){
    Active.update({_id:id},{'$inc':{applyNum:num}},function(err){
        callback(err);
    })
}
Active.prototype.applyActive=function(id,applyId,callback){
    Active.update({_id:id},{'$addToSet':{applyUsers:applyId},'$inc':{applyNum:1}},function(err){
        callback(err);
    })
}
Active.prototype.cancelActive=function(id,applyId,callback){
    Active.update({_id:id},{'$pull':{applyUsers:applyId},'$inc':{applyNum:-1}},function(err){
        callback(err);
    })
}
Active.prototype.findForPage=function(obj,callback){
    var q=obj.search||{};                                       //查询条件
    var col=obj.columns||{};                                    //返回字段
    var query=Active.find(q,col).skip(obj.page.skipFrom).limit(obj.page.limit);
    query.exec(function(err, datas) {
        if (err) {
            callback(err, null, null);
        } else {
            Active.count(q, function(err, count) {
                if (err) {
                    callback(err, null, null);
                } else {
                    var pageCount = Math.ceil(count / obj.page.limit);
                    callback(null, count,pageCount, datas);
                }
            });
        }
    });

}
module.exports =Active;
module.exports.activeSchema=activeSchema;


